from flask_wtf import FlaskForm
from wtforms import StringField, BooleanField, IntegerField, SubmitField, SelectField, TextAreaField
from wtforms.validators import DataRequired, Length, Optional, NumberRange, Regexp
from ....models import Category
from . import Unique
from flask import Markup


class EditForm(FlaskForm):
    parent_id = SelectField('上级栏目', coerce=int)
    title = StringField('栏目名称', validators=[
        DataRequired(message='栏目名称必须'),
        Length(min=1, max=30, message='栏目名称长度需1~30个字之间'),
        Unique(model=Category, model_field=Category.title, message='已存在的栏目名称')
    ])
    keyword = StringField('关键词', validators=[
        Optional(),
        Length(min=1, max=30, message='关键词长度需1~30个字之间')
    ])
    intro = TextAreaField('栏目简介', validators=[
        Optional(),
        Length(min=1, max=128, message='栏目简介长度需1~128个字之间')
    ])
    thumbnail = StringField('封面', validators=[
        Optional(),
        Length(min=1, max=128, message='栏目名称长度需1~30个字之间')
    ])
    path = StringField('路径标识', validators=[
        Regexp('^[a-zA-Z\d_]{1,20}$', message='有效的路径只能为数字,字母以及下划线_,并且合法长度为3-20'),
        Unique(model=Category, model_field=Category.path, message='已存在的路径标识')
    ])
    number = IntegerField('显示数量', default=20, validators=[
        NumberRange(min=10, max=50, message='显示数量需10~50之间')
    ])
    is_menu = BooleanField('设为菜单', default=True)
    menu_name = StringField(
        '菜单名',
        validators=[
            Optional(),
            Length(min=1, max=30, message='菜单名长度需1~30个字之间'),
            Unique(model=Category, model_field=Category.menu_name, message='已存在的菜单名')
        ],
        render_kw={
            'placeholder': '如为空，则以栏目名称作为菜单名'
        }
    )
    grade = IntegerField('栏目排序', default=1, validators=[
        NumberRange(min=0, max=5000, message='数值已超出0~5000的合法范围')
    ])

    save = SubmitField('保存')

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.parent_id.choices = [(0, '顶级栏目')]
        for item in Category.html_tree():
            length = len(item.level.split('-'))
            if length == 1:
                _str = ''
            elif length == 2:
                _str = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'
            else:
                _str = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' * (length - 1)
            self.parent_id.choices.append(
                (
                    item.id,
                    Markup(_str + item.mark + item.title)
                )
            )